<template>
  <div class="order-detail-container">
    <div class="page-header">
      <h1>订单详情</h1>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/user/order/list' }">我的订单</el-breadcrumb-item>
        <el-breadcrumb-item>订单详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <div class="detail-container" v-loading="loading">
      <template v-if="order">
        <!-- 订单状态卡片 -->
        <div class="status-card">
          <div class="status-header">
            <div class="status-info">
              <div class="status-label">当前状态</div>
              <div class="status-value">
                <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
              </div>
            </div>
            <div class="actions">
              <el-button 
                type="primary" 
                size="small" 
                v-if="order.status === 0"
                @click="showPaymentDialog">
                去支付
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                v-if="order.status === 0"
                @click="cancelOrder">
                取消订单
              </el-button>
              <el-button 
                type="primary" 
                plain
                size="small" 
                @click="$router.push('/user/order/list')">
                返回列表
              </el-button>
            </div>
          </div>
          
          <el-steps :active="getStatusStep(order.status)" align-center finish-status="success" class="status-steps">
            <el-step title="已下单" :description="formatDate(order.createTime)"></el-step>
            <el-step title="已支付" :description="order.paymentTime ? formatDate(order.paymentTime) : '-'"></el-step>
            <el-step title="处理中" :description="order.processTime ? formatDate(order.processTime) : '-'"></el-step>
            <el-step title="已完成" :description="order.completeTime ? formatDate(order.completeTime) : '-'"></el-step>
          </el-steps>
        </div>

        <!-- 订单信息卡片 -->
        <el-row :gutter="20" class="info-row">
          <el-col :xs="24" :sm="24" :md="16" :lg="16">
            <el-card shadow="never" class="order-card">
              <div slot="header" class="order-header">
                <span class="card-title">订单信息</span>
                <div class="order-number">
                  <span>订单号：{{ order.orderNo }}</span>
                  <el-button 
                    type="text" 
                    icon="el-icon-copy-document" 
                    @click="copyOrderNo">
                    复制
                  </el-button>
                </div>
              </div>
              
              <div class="order-info">
                <div class="info-item">
                  <div class="info-icon service-icon" :class="getServiceIconClass(order.serviceTypeId)"></div>
                  <div class="info-content">
                    <div class="info-title">服务类型</div>
                    <div class="info-value">{{ order.serviceTypeName }}</div>
                  </div>
                </div>
                
                <div class="info-item">
                  <div class="info-icon clothes-icon" :class="getClothesIconClass(order.clothesTypeId)"></div>
                  <div class="info-content">
                    <div class="info-title">衣物类型</div>
                    <div class="info-value">{{ order.clothesTypeName }}</div>
                  </div>
                </div>
                
                <div class="info-item">
                  <div class="info-icon quantity-icon"></div>
                  <div class="info-content">
                    <div class="info-title">衣物数量</div>
                    <div class="info-value">{{ order.quantity }} 件</div>
                  </div>
                </div>
                
                <div class="info-item full-width">
                  <div class="info-icon address-icon"></div>
                  <div class="info-content">
                    <div class="info-title">取件地址</div>
                    <div class="info-value">{{ order.pickupAddress }}</div>
                  </div>
                </div>
                
                <div class="info-item full-width" v-if="order.remark">
                  <div class="info-icon remark-icon"></div>
                  <div class="info-content">
                    <div class="info-title">备注信息</div>
                    <div class="info-value">{{ order.remark }}</div>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :sm="24" :md="8" :lg="8">
            <el-card shadow="never" class="price-card">
              <div slot="header" class="price-header">
                <span class="card-title">费用信息</span>
              </div>
              
              <div class="price-detail">
                <div class="price-item">
                  <span>服务单价</span>
                  <span>¥{{ order.serviceTypePrice || '-' }}</span>
                </div>
                <div class="price-item">
                  <span>衣物数量</span>
                  <span>× {{ order.quantity }}</span>
                </div>
                <div class="price-divider"></div>
                <div class="price-total">
                  <span>订单总价</span>
                  <span class="total-amount">¥{{ order.totalAmount }}</span>
                </div>
                
                <div class="payment-info" v-if="order.status > 0">
                  <div class="payment-label">支付方式</div>
                  <div class="payment-value">
                    <img 
                      :src="getPaymentMethodIcon(order.paymentMethod)" 
                      class="payment-icon" 
                      v-if="order.paymentMethod">
                    {{ getPaymentMethodText(order.paymentMethod) || '未知' }}
                  </div>
                  <div class="payment-time" v-if="order.paymentTime">
                    支付时间：{{ formatDate(order.paymentTime) }}
                  </div>
                </div>
              </div>
            </el-card>
            
            <el-card shadow="never" class="timeline-card" v-if="orderLogs && orderLogs.length > 0">
              <div slot="header" class="timeline-header">
                <span class="card-title">订单动态</span>
              </div>
              
              <el-timeline>
                <el-timeline-item
                  v-for="(log, index) in orderLogs"
                  :key="index"
                  :timestamp="formatDate(log.createTime)"
                  :type="index === 0 ? 'primary' : ''"
                  :size="index === 0 ? 'large' : 'normal'"
                  placement="top">
                  {{ log.content }}
                </el-timeline-item>
              </el-timeline>
            </el-card>
          </el-col>
        </el-row>
      </template>
      
      <div class="empty-state" v-else-if="!loading">
        <i class="el-icon-document"></i>
        <p>订单不存在或已被删除</p>
        <el-button type="primary" @click="$router.push('/user/order/list')">返回订单列表</el-button>
      </div>
    </div>
    
    <!-- 支付对话框 -->
    <el-dialog title="订单支付" :visible.sync="paymentDialogVisible" width="400px" center>
      <div class="payment-dialog">
        <div class="payment-amount">
          <div class="amount-label">支付金额</div>
          <div class="amount-value">¥{{ order ? order.totalAmount : '0.00' }}</div>
        </div>
        <div class="payment-methods">
          <div class="method-label">支付方式</div>
          <div class="method-options">
            <el-radio v-model="paymentMethod" label="alipay">
              <img src="@/assets/alipay.png" alt="支付宝" class="payment-icon">
              支付宝
            </el-radio>
            <el-radio v-model="paymentMethod" label="wechat">
              <img src="@/assets/wechat.png" alt="微信支付" class="payment-icon">
              微信支付
            </el-radio>
          </div>
        </div>
        <div class="payment-qrcode">
          <img :src="getPaymentQRCode()" alt="支付二维码" class="qrcode-image">
          <p>请使用{{ paymentMethod === 'alipay' ? '支付宝' : '微信' }}扫码支付</p>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { formatDate } from '@/utils/date'

export default {
  name: 'OrderDetail',
  data() {
    return {
      orderId: null,
      order: null,
      orderLogs: [],
      loading: true,
      paymentDialogVisible: false,
      paymentMethod: 'alipay'
    }
  },
  created() {
    this.orderId = this.$route.params.id
    this.fetchOrderDetail()
    this.fetchOrderLogs()
  },
  methods: {
    formatDate,
    async fetchOrderDetail() {
      try {
        const res = await axios.get(`/api/order/detail/${this.orderId}`).then(res => res.data)
        if (res.code === 200) {
          this.order = res.data
        } else {
          this.$message.error(res.message || '获取订单详情失败')
        }
      } catch (error) {
        this.$message.error('获取订单详情失败')
      } finally {
        this.loading = false
      }
    },
    async fetchOrderLogs() {
      try {
        const res = await axios.get(`/api/order/logs/${this.orderId}`).then(res => res.data)
        if (res.code === 200) {
          this.orderLogs = res.data
        }
      } catch (error) {
        console.error('获取订单日志失败', error)
      }
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付待取件',
        2: '已取件处理中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'primary',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || 'info'
    },
    getStatusStep(status) {
      // 将状态值映射到步骤索引
      const stepMap = {
        0: 0, // 已下单
        1: 1, // 已支付
        2: 2, // 处理中
        3: 3, // 已完成
        4: 0  // 已取消（仍然显示已下单状态）
      }
      return stepMap[status] || 0
    },
    getServiceIconClass(serviceTypeId) {
      // 根据服务类型ID返回不同的图标类
      const classes = [
        'service-icon-wash',
        'service-icon-iron',
        'service-icon-dry',
        'service-icon-special'
      ]
      return classes[serviceTypeId % classes.length] || classes[0]
    },
    getClothesIconClass(clothesTypeId) {
      // 根据衣物类型ID返回不同的图标类
      const classes = [
        'clothes-icon-tshirt',
        'clothes-icon-pants',
        'clothes-icon-dress',
        'clothes-icon-coat'
      ]
      return classes[clothesTypeId % classes.length] || classes[0]
    },
    getPaymentMethodText(method) {
      const methodMap = {
        'alipay': '支付宝',
        'wechat': '微信支付',
        'cash': '现金支付',
        'card': '银行卡支付'
      }
      return methodMap[method] || '未知支付方式'
    },
    getPaymentMethodIcon(method) {
      // 返回支付方式对应的图标
      if (method === 'alipay') {
        return 'https://via.placeholder.com/24x24?text=Alipay'
      } else if (method === 'wechat') {
        return 'https://via.placeholder.com/24x24?text=WeChat'
      }
      return ''
    },
    copyOrderNo() {
      // 创建临时输入框，复制文本到剪贴板
      const input = document.createElement('input')
      input.value = this.order.orderNo
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
      this.$message.success('订单号已复制到剪贴板')
    },
    showPaymentDialog() {
      if (this.order && this.order.status === 0) {
        this.paymentDialogVisible = true
      }
    },
    getPaymentQRCode() {
      // 返回支付方式对应的二维码图片
      return this.paymentMethod === 'alipay' 
        ? 'https://example.com/alipay_qrcode.png' 
        : 'https://example.com/wechat_qrcode.png'
    },
    async confirmPayment() {
      try {
        if (!this.order) return
        
        const res = await axios.put(`/api/order/pay?orderNo=${this.order.orderNo}&paymentMethod=${this.paymentMethod}`).then(res => res.data)
        
        if (res.code === 200) {
          this.$message.success('支付成功')
          this.paymentDialogVisible = false
          // 刷新订单详情
          this.fetchOrderDetail()
          this.fetchOrderLogs()
        } else {
          this.$message.error(res.message || '支付失败')
        }
      } catch (error) {
        this.$message.error('支付操作失败')
      }
    },
    async cancelOrder() {
      try {
        await this.$confirm('确定要取消该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await axios.put(`/api/order/cancel?orderNo=${this.order.orderNo}`).then(res => res.data)
        if (res.code === 200) {
          this.$message.success('订单已取消')
          // 刷新订单详情
          this.fetchOrderDetail()
          this.fetchOrderLogs()
        } else {
          this.$message.error(res.message || '取消订单失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('取消订单失败')
        }
      }
    }
  }
}
</script>

<style scoped>
.order-detail-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 30px 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  color: #333;
  margin: 0 0 15px 0;
}

.detail-container {
  margin-bottom: 40px;
  min-height: 300px;
}

/* 订单状态卡片 */
.status-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.status-info {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 1rem;
  color: #606266;
  margin-right: 15px;
}

.status-value {
  font-size: 1rem;
}

.status-steps {
  margin-top: 20px;
}

/* 信息行样式 */
.info-row {
  margin-bottom: 20px;
}

/* 订单信息卡片 */
.order-card, .price-card, .timeline-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.order-header, .price-header, .timeline-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.card-title {
  font-size: 1.1rem;
  font-weight: bold;
  color: #333;
}

.order-number {
  float: right;
  color: #606266;
  display: flex;
  align-items: center;
}

.order-info {
  padding: 15px 0;
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  width: 50%;
  margin-bottom: 20px;
  padding-right: 10px;
}

.info-item.full-width {
  width: 100%;
}

.info-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
  border-radius: 8px;
  background-color: #f5f7fa;
  background-size: 24px;
  background-position: center;
  background-repeat: no-repeat;
}

.service-icon-wash {
  background-image: url('https://img.icons8.com/color/96/000000/washing-machine.png');
}

.service-icon-iron {
  background-image: url('https://img.icons8.com/color/96/000000/iron.png');
}

.service-icon-dry {
  background-image: url('https://img.icons8.com/color/96/000000/clothes-line.png');
}

.service-icon-special {
  background-image: url('https://img.icons8.com/color/96/000000/dry-clean.png');
}

.clothes-icon-tshirt {
  background-image: url('https://img.icons8.com/color/96/000000/t-shirt.png');
}

.clothes-icon-pants {
  background-image: url('https://img.icons8.com/color/96/000000/jeans.png');
}

.clothes-icon-dress {
  background-image: url('https://img.icons8.com/color/96/000000/dress.png');
}

.clothes-icon-coat {
  background-image: url('https://img.icons8.com/color/96/000000/winter-jacket.png');
}

.quantity-icon {
  background-image: url('https://img.icons8.com/color/96/000000/in-inventory.png');
}

.address-icon {
  background-image: url('https://img.icons8.com/color/96/000000/address.png');
}

.remark-icon {
  background-image: url('https://img.icons8.com/color/96/000000/note.png');
}

.info-content {
  flex: 1;
}

.info-title {
  color: #909399;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.info-value {
  color: #333;
  word-break: break-word;
}

/* 价格卡片样式 */
.price-detail {
  padding: 15px 0;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #606266;
}

.price-divider {
  height: 1px;
  background-color: #f0f0f0;
  margin: 15px 0;
}

.price-total {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 20px;
}

.total-amount {
  color: #f56c6c;
  font-size: 1.2rem;
}

.payment-info {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
}

.payment-label {
  color: #606266;
  font-size: 0.9rem;
  margin-bottom: 10px;
}

.payment-value {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: bold;
}

.payment-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

.payment-time {
  color: #909399;
  font-size: 0.9rem;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background-color: white;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.empty-state i {
  font-size: 80px;
  color: #dcdfe6;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 1.1rem;
  color: #909399;
  margin-bottom: 20px;
}

/* 支付对话框样式 */
.payment-dialog {
  text-align: center;
}

.payment-amount {
  margin-bottom: 20px;
}

.amount-label {
  font-size: 1rem;
  color: #606266;
  margin-bottom: 10px;
}

.amount-value {
  font-size: 2rem;
  font-weight: bold;
  color: #f56c6c;
}

.payment-methods {
  margin-bottom: 20px;
}

.method-label {
  font-size: 1rem;
  color: #606266;
  margin-bottom: 10px;
  text-align: left;
}

.method-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.payment-icon {
  width: 24px;
  height: 24px;
  margin-right: 10px;
  vertical-align: middle;
}

.payment-qrcode {
  margin: 20px 0;
}

.qrcode-image {
  width: 180px;
  height: 180px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .status-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .status-info {
    margin-bottom: 15px;
  }
  
  .info-item {
    width: 100%;
  }
  
  .order-number {
    float: none;
    margin-top: 10px;
  }
}
</style> 